import React, { useState, useEffect, useRef } from 'react';
import { Skeleton, App } from 'antd';
import loadable from '@loadable/component';

import { HOME } from '@/config/url';
import { insertScript } from '@/utils';
import styles from './index.module.scss';

const SmsLoginForm = loadable(() => import('./SmsLoginForm'), { fallback: <Skeleton active/> });

export default (props) => {
    const container = useRef(null);
    const { message } = App.useApp();

    const removeBubbly = () => {
        const ele = document.getElementById('bubbly-canvas');
        if(!ele) return;

        ele.parentNode.removeChild(ele);
    }

    // 登录成功
    const onOk = () => {
        message.success(`登录成功，即将跳转`);

        // 移除背景
        removeBubbly();

        let t = setTimeout(() => {
            clearTimeout(t);

            location.href = HOME;
        }, 500);
    };
    const onCancel = () => {};

    // 初始化背景
    const initBubblyBg = () => {
        // 这里的色值没有也无需动态获取，写死的
        if(!window.bubbly) return;

        bubbly({
            bubbles: {
                count: 32,
                radius: () =>4 + Math.random() * window.innerWidth / 25,
                fill: () =>`hsla(151.3deg, 90.2%, 80%, ${Math.random() * 0.1})`,
                angle: () =>Math.random() * Math.PI * 2,
                velocity: () =>0.1 + Math.random() * 0.5,
                shadow: () => (null),
                stroke: () => ({color: "rgba(255, 255, 255, 0.1)", width: Math.random() * 1}),
            },
            background: (ctx) => {
                const gradient = ctx.createLinearGradient(0, 0, ctx.canvas.width, ctx.canvas.height);
                gradient.addColorStop(0, "#77F8B8");
                gradient.addColorStop(1, "#00C261");
                return gradient;
            },
            animate: true,
        });
    };

    useEffect(() => {
        const url = `${BASEDIR}/js/bubbly.min.js`;
        const scriptId = insertScript(url, initBubblyBg);

        return () => {
            const ele = document.getElementById(scriptId);
            if(ele) {
                ele.parentNode.removeChild(ele);
                delete window.bubbly;
            }
        }
    }, []);

    return (
        <div className={styles['container']} ref={container} id="login">
            <div className={styles['form-container']}>
                <h2>欢迎来到&nbsp;{WEB_NAME}</h2>
                <SmsLoginForm
                    onOk={onOk}
                    onCancel={onCancel}
                />
            </div>
        </div>
    );
};